<template>
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
                        <div>
                            <form class="form-inline" onsubmit="return false;">

                                <div class="row">
                                    <div class="form-group">
                                        <label class="sr-only" for="example-if-password">用户名</label>
                                        <input class="form-control" type="text" placeholder="用户名" v-model="nickname">
                                    </div>
                                    <div class="form-group">
                                        <label class="sr-only" for="mobile">手机号</label>
                                        <input class="form-control" type="text" placeholder="手机号" v-model="mobile">
                                    </div>
                                    <div class="form-group">
                                        <el-select v-model="isVip" placeholder="是否会员">
                                            <el-option
                                                    v-for="item in options"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </div>

                                    <div class="input-daterange input-group" style="width:30%;margin-left: 8px;">
                                        <el-date-picker
                                                v-model="startTime"
                                                type="date"
                                                format="yyyy-MM-dd"
                                                @change="getStartTime"
                                                placeholder="选择日期">
                                        </el-date-picker>
                                        <span class="input-group-addon"><i class="mdi mdi-chevron-right"></i></span>
                                        <el-date-picker
                                                v-model="endTime"
                                                type="date"
                                                @change="getEndTime"
                                                format="yyyy-MM-dd"
                                                placeholder="选择日期">
                                        </el-date-picker>
                                    </div>
                                </div>

                                <div class="row" style="margin-top:15px;">

                                    <div class="form-group">
                                        <el-select v-model="isFollow" placeholder="是否关注">
                                            <el-option
                                                    v-for="item in followOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </div>

                                    <div class="form-group">
                                        <label class="sr-only">用户ID</label>
                                        <input class="form-control" type="text" placeholder="用户ID" v-model="userId">
                                    </div>

                                    <div class="form-group">
                                        <!--<label class="el-form-item__label" style="width: 120px;">关联分类</label>-->
                                        <el-autocomplete
                                                v-model="companyName"
                                                :fetch-suggestions="queryCompanyAsync"
                                                placeholder="公司/品牌"
                                                @select="handleSearchSelect"
                                                style="width: 100%"
                                        >
                                        </el-autocomplete>
                                    </div>
                                    <div class="form-group">
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in tags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleSearchClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </div>
                                    <div class="form-group" style="float:right;margin-right:100px;">
                                        <button class="btn btn-success" type="submit" v-on:click="search()">筛选</button>
                                    </div>
                                </div>


                            </form>
                        </div>
                        <div class="table-responsive" style="width: 100%;margin-top: 20px;" v-loading="loading">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                            >
                                <el-table-column
                                        prop="userId"
                                        label="用户ID"
                                        width="70">
                                </el-table-column>
                                <el-table-column
                                        prop="nickname"
                                        label="用户名"
                                        width="100">
                                    <template slot-scope="scope">
                                        <a @click="openEdit(scope.row._id)" style="cursor:pointer;">{{
                                            scope.row.nickname }}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="companyStr"
                                        label="关注公司"
                                        :formatter="formatCompany"
                                        width="100">
                                </el-table-column>
                                <el-table-column
                                        prop="isFollow"
                                        label="关注状态"
                                        :formatter="formatFollow"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="isVip"
                                        label="开通会员"
                                        :formatter="formatVip"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="recommendName"
                                        label="直接代理"
                                        :formatter="formatRecommendName"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="highLevel"
                                        label="高级代理"
                                        :formatter="formatHighLevelName"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="mobile"
                                        label="手机号"
                                        :formatter="formatMobile"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="注册时间"
                                        align="center"
                                        width="170">
                                </el-table-column>
                                <el-table-column
                                        label="操作"
                                        align="center"
                                        width="170"
                                >
                                    <template slot-scope="scope">
                                        <el-button size="mini" @click="handleEdit(scope.row)">设置</el-button>

                                        <el-button size="mini" type="success" @click="handleStatus(scope.row._id,0)"
                                                   v-if="scope.row.status===1">禁用
                                        </el-button>
                                        <el-button size="mini" @click="handleStatus(scope.row._id,1)"
                                                   v-if="scope.row.status===0">开启
                                        </el-button>
                                    </template>

                                </el-table-column>
                            </el-table>

                            <nav style="margin-top: 20px">
                                <el-pagination
                                        layout="total, sizes, prev, pager, next"
                                        :total="total"
                                        :hide-on-single-page="pageActive"
                                        @size-change="handleSizeChange"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        :page-sizes="[10, 20, 30, 40]"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>

                            <el-dialog title="用户设置" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                                <el-form :model="form">

                                    <!--<el-form-item label="关联分类" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.categoryName"
                                                :fetch-suggestions="queryIndustrySearchAsync"
                                                placeholder="请输入内容"
                                                @select="handleIndustryQuerySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in form.categoryTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleIndustryClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>-->

                                    <el-form-item label="关联公司" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.companyName"
                                                :fetch-suggestions="queryCompanyAsync"
                                                placeholder="请输入内容"
                                                @select="handleCompanySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in form.companyTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleCompanyClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>
                                </el-form>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="submitSet">确 定</el-button>
                                </div>
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

    import common from '../../api/public.js';

    export default {
        name: "WechatUserComponent",
        data() {
            return {
                userId: '',
                nickname: '',
                mobile: '',
                startTime: '',
                endTime: '',
                pageActive: true,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: 1,
                isVip: -1,
                isFollow: -1,
                options: [{
                    value: -1,
                    label: '全部-是否会员'
                }, {
                    value: 1,
                    label: '会员'
                }, {
                    value: 0,
                    label: '非会员'
                }],
                followOptions: [{
                    value: -1,
                    label: '全部-是否关注'
                }, {
                    value: 1,
                    label: '关注中'
                }, {
                    value: 0,
                    label: '已取关'
                }],

                form: {
                    categoryName: '',
                    companyName: '',
                    companyTags: [],
                    companyIds: [],
                    /*categoryTags: [],
                    categoryIds: [],*/
                    nickname: '用户内容'
                },
                dialogFormVisible: false,
                formLabelWidth: '120px',
                id: "",
                order: 'desc',
                orderField: '_id',
                tags: [],
                ids: [],
                companyName: '',
                restaurants: [],
                companies: []
            }
        },
        methods: {
            ...common,
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            handleSizeChange: function (pageSize) {
                this.pageSize = pageSize;
                this.search();
            },
            search: function () {
                let self = this;
                let uri = 'wechat-user/post-list';
                self.loading = true;

                let postData = {
                    startTime: self.startTime,
                    endTime: self.endTime,
                    page: self.currentPage,
                    limit: self.pageSize,
                    status: self.status,
                    userId: self.userId,
                    nickname: self.nickname,
                    mobile: self.mobile,
                    isVip: self.isVip,
                    isFollow: self.isFollow,
                    companyIds: self.ids
                };

                axios.post(uri, postData).then(function (result) {
                    self.total = result.wechatUsers.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.wechatUsers.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            getStartTime(date) {
                this.startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            },
            getEndTime: function (date) {
                this.endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            },
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/" + keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async queryIndustrySearchAsync(queryString, cb) {
                await this.queryIndustry(queryString);
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleIndustryQuerySelect(item) {
                if (item && this.form.categoryIds.indexOf(item.id) === -1) {
                    this.form.categoryTags.push(item);
                    this.form.categoryIds.push(item.id);
                }
                this.form.categoryName = '';
            },
            handleIndustryClose(tag) {
                this.form.categoryTags.splice(this.form.categoryTags.indexOf(tag), 1);
                this.form.categoryIds.splice(this.form.categoryIds.indexOf(tag.id));
            },
            async queryCompany(keyword = '') {
                let self = this;
                let uri = "company/search/" + keyword;

                axios.get(uri).then(function (result) {
                    self.companies = result.list;
                });
            },
            async queryCompanyAsync(queryString, cb) {

                await this.queryCompany(queryString);
                var restaurants = this.companies;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleCompanySelect(item) {
                if (item && this.form.companyIds.indexOf(item.id) === -1) {
                    this.form.companyTags.push(item);
                    this.form.companyIds.push(item.id);
                }
                this.form.companyName = '';
            },
            handleCompanyClose(tag) {
                this.form.companyTags.splice(this.form.companyTags.indexOf(tag), 1);
                this.form.companyIds.splice(this.form.companyIds.indexOf(tag.id), 1);
            },

            handleSearchSelect(item) {
                if (item && this.ids.indexOf(item.id) === -1) {
                    this.tags.push(item);
                    this.ids.push(item.id);
                }
            },
            handleSearchClose(tag) {
                this.tags.splice(this.tags.indexOf(tag), 1);
                this.ids.splice(this.ids.indexOf(tag.id), 1);
            },
            formatFollow(row) {
                return row.isFollow === 1 ? '关注中' : (row.isFollow== -1 ? '用户授权未关注' : '已取关');
            },
            formatVip(row) {
                return row.isVip === 1 ? '会员' : '非会员';
            },
            formatCompany(row) {
                return this.filterLength(row.companyStr, 6);
            },
            filterLength: function (str, length = 9) {
                if (str.length >= length) {
                    return str.substring(0, length) + '...';
                }
                return str.length === 0 ? '--' : str;
            },
            formatRecommendName(row) {
                return !row.recommendName ? '--' : row.recommendName;
            },
            formatHighLevelName(row) {
                return !row.highLevelName ? '--' : row.highLevelName;
            },
            formatMobile(row) {
                return !row.mobile ? '--' : row.mobile;
            },
            handleEdit(row) {
                this.form.categoryName = '';
                this.form.companyName = '';
                this.form.companyTags = [];
                //this.form.categoryTags = [];
                this.form.companyIds = [];
                //this.form.categoryIds = [];
                this.id = '';

                this.form.companyTags = row.companies;
                //this.form.categoryTags = row.categoryNames;
                this.form.nickname = row.nickname;
                this.id = row._id;

                /*row.categoryNames.forEach((item) => {
                    this.form.categoryIds.push(item.id)
                });*/

                row.companies.forEach((item) => {
                    this.form.companyIds.push(item.id)
                });

                this.dialogFormVisible = true;

            },
            submitSet() {
                let self = this;
                let categoryIds = this.form.categoryIds;
                let companyIds = this.form.companyIds;
                self.loading = true;
                let uri = "wechat-user/set/" + self.id;
                let data = {companyIds: companyIds, categoryIds: categoryIds};

                axios.put(uri, data).then(function (result) {
                    self.dialogFormVisible = false;
                    self.search();
                });
            },
            handleStatus: function (id, status) {

                let self = this;
                let uri = "wechat-user/set-status/" + id + "/" + status;
                axios.get(uri).then(function (result) {
                    self.search();
                });
            },
            openEdit(id) {
                this.openUri('wechat-user/detail/' + id);
            },

        },
        mounted() {
            this.search();
            this.queryCompany();
            this.queryIndustry();
        }
    }
</script>

<style scoped>
    .el-input--suffix .el-input__inner {
        padding-right: 0;
    }

    .card-body .el-input__icon {
        /*height: 100%;
        width: 25px;*/
        width: 0;
        text-align: center;
        -webkit-transition: all .3s;
        transition: all .3s;
        line-height: 40px;
    }
</style>
